package com.xxgc.mybatis.dao;

import com.xxgc.mybatis.po.User;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Map;

//用户表Dao层接口
public interface UserDao {
    //查询所有用户
    @Select("select * from users")
    @Results(id ="userMap",value = {
            @Result(property = "uId",column = "u_id"),
            @Result(property = "uName",column = "u_name"),
            @Result(property = "uPass",column = "u_pass")
    })
//    @ResultMap("userMap")
    List<User> selectAllUsers();
    //通过id查询用户
    @Select("select * from users where u_id = #{uId}")

    @ResultMap("userMap")
    User selectUserById(@Param("uId") int uId);
    //插入一个用户
    @Insert("INSERT INTO `users`(`u_name`,`u_pass`) VALUE(#{uName},#{uPass})")
    int addUser(User user);
    //修改用户
    @Update("UPDATE  `users` SET `u_name` = #{uName} where u_id = #{uId}")
    int updateUser(User user);
    //删除用户
    @Delete("DELETE FROM `users` WHERE `u_id` = #{uId}")
    int deleteUserById(int uId);
    //特殊的参数传递
    @Insert("INSERT INTO `users`(`u_name`,`u_pass`) VALUE(#{myName},#{myPass})")
    int addUserByMap(Map<String, Object> map);
    //模糊查询
    @Select("SELECT * FROM `users` where u_name LIKE CONCAT('%', #{name}, '%')")
    @ResultMap("userMap")
    List<User> selectUsersByLike(String name);

    //    @SelectProvider(type="类名.class")  会去调用方法  方法返回值必须是一个String  sql语句
    @SelectProvider(type = UserProvider.class,method = "selectUser")
    List<User> selectUserbyAttr(@Param("uId") Integer uId,@Param("uName") String uName);


    /**
     * 内部类
     */
    class UserProvider{
        /**
         * 自定义方法
         * @return
         */
        public String selectUser(Map<String,Object> map){
            String  sql = "SELECT * FROM `users` where 1=1 ";
            if(map.get("uId") !=null){
                sql+= " and u_id = #{uId} ";
            }
            if(map.get("uName") != null && "".equals(map.get("uName"))){
                sql+= " and u_name = #{uName} ";
            }

            System.out.println("sql = " + sql);
            return sql;
        }
    }

    @Select({"<script>",
            "SELECT * FROM `users`",
            "<where>",
                "<if test='uId != null'>",
                    "and u_id = #{uId}",
                "</if>",
                "<if test='uName != null'>",
                "and u_name = #{uName}",
                "</if>",
            "</where>",
            "</script>"


    })
    List<User> selectUserbyAttr2(@Param("uId") Integer uId,@Param("uName") String uName);











}
